package segger.vasttrafik;

import java.util.TimerTask;

import org.apache.log4j.Logger;

import segger.vasttrafik.API.URLBuilder;
import segger.vasttrafik.io.APIConnection;
import segger.vasttrafik.parsing.TimeTableParseHandler;

public class TimeTableTask extends TimerTask {
    private static final Logger logger = Logger.getLogger(TimeTableTask.class);
    
    private UpdateListener listener;
    private URLBuilder urlBuilder;
    private APIConnection connection;

    private TimeTableParseHandler myHandler = new TimeTableParseHandler();

    private Location location;
    
    public TimeTableTask(Location location, UpdateListener listener) {
        this.location = location;
        this.listener = listener;
        urlBuilder = API.getInstance().getURLBuilder(API.SERVICE_DEPARTURE);
        connection = new APIConnection();
    }
    
    @Override
    public void run() {
        logger.debug("running");
        String stopID = location.getStopID();
        if(stopID != null) {
            urlBuilder.input(stopID);
            connection.httpGet(urlBuilder.getURL(), myHandler);
            updateListener();
        } else {
            logger.debug("no stop id yet");
        }
    }

    private void updateListener() {
        TimeTable timeTable = myHandler.getTimeTable();
        if(listener != null) {
            if(timeTable != null) {
                listener.updated(timeTable);
            } else {
                listener.updateError("No time table available");
            }
        }
    }

}
